package com.gitee.faster.webdav.kernel.resource;

import cn.hutool.core.util.ServiceLoaderUtil;
import com.gitee.faster.webdav.kernel.resource.local.LocalResourceRepository;
import lombok.Getter;

import java.util.List;

/**
 * 根据请求创建资源与资源库
 *
 * @author hongda.li
 */
@Getter
@SuppressWarnings({"rawtypes", "unchecked"})
public final class ResourceRepositoryFactory {
    /**
     * 单例模式
     */
    private static final ResourceRepositoryFactory INSTANCE = new ResourceRepositoryFactory();

    /**
     * 本地资源库
     */
    private final ResourceRepository localResourceRepository;

    /**
     * 远程资源库集合
     */
    private final List<ResourceRepositoryIntegrable> remoteRepositoryList;

    private ResourceRepositoryFactory() {
        this.localResourceRepository = new LocalResourceRepository();
        this.remoteRepositoryList = ServiceLoaderUtil.loadList(ResourceRepositoryIntegrable.class);
    }

    /**
     * 获取单例
     *
     * @return 全局唯一单例
     */
    public static ResourceRepositoryFactory getInstance() {
        return INSTANCE;
    }

    /**
     * 初始化资源
     *
     * @param path 请求路径
     * @return 资源实例
     */
    public ResourceRepository<Resource> findRepository(String path) {
        for (ResourceRepositoryIntegrable repositoryRemote : this.remoteRepositoryList) {
            if (repositoryRemote.accept(path)) {
                return repositoryRemote;
            }
        }
        return this.localResourceRepository;
    }
}
